﻿using BaiTu.Common.Web.Helpers;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace BaiTu.Common.Web
{
    /// <summary>
    /// 用于响应客户端的请求
    /// </summary>
    public class BaiTuResponse
    {
        /// <summary>
        /// 以指定的ContentType输出指定文件文件
        /// </summary>
        /// <param name="filepath">文件路径</param>
        /// <param name="filename">输出的文件名</param>
        /// <param name="filetype">将文件输出时设置的ContentType</param>
        public static void ResponseFile(string filePath, string fileName, string fileType)
        {
            if (Common.Helpers.FileHelper.FileExists(filePath).Success == false)
            {
                throw new Framework.Exceptions.BaiTuCoreException(string.Format("文件不存在，文件路径为:{0}", filePath));
            }
            Stream outputStream = null;
            //设置缓冲区为10K
            byte[] buffer = new byte[10000];
            //文件长度
            int length;
            //需要读取的数据长度
            long dataToRead;

            try
            {
                // 打开文件
                outputStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

                // 需要读的数据长度
                dataToRead = outputStream.Length;

                HttpContext.Current.Response.ContentType = fileType;
                if (BrowserHelper.IsIE() == true)
                    HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + EncodeHelper.UrlEncode(fileName.Trim()).Replace("+", " "));
                else
                    HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName.Trim());

                while (dataToRead > 0)
                {
                    // 检查客户端是否还处于连接状态
                    if (HttpContext.Current.Response.IsClientConnected)
                    {
                        length = outputStream.Read(buffer, 0, 10000);
                        HttpContext.Current.Response.OutputStream.Write(buffer, 0, length);
                        HttpContext.Current.Response.Flush();
                        buffer = new Byte[10000];
                        dataToRead = dataToRead - length;
                    }
                    else
                    {
                        // 如果不再连接则跳出死循环
                        dataToRead = -1;
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Framework.Exceptions.BaiTuCoreException("以指定的ContentType输出指定文件文件,出现异常", ex);
            }
            finally
            {
                if (outputStream != null)
                {
                    // 关闭文件
                    outputStream.Close();
                }
            }
            HttpContext.Current.Response.End();
        }
    }
}
